<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="javax.jdo.Query" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="com.smwish.Wish" %>
<%@ page import="com.smwish.WishUtil" %>
<%@ page import="com.smwish.PMF" %>

<html>
  <head>
  	<title>神马的梦想</title>
    <link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
    <link type="text/css" rel="stylesheet" href="/stylesheets/sliding.css"  media="screen" />
	<script language="javascript">
		var xmlHttp;
		function createXMLHttpRequest(){
			if(window.ActiveXObject){
  				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} else if(window.XMLHttpRequest){
  				xmlHttp=new XMLHttpRequest();
  			}
  		}
		
		function voteViaPost( key )
		{
			 createXMLHttpRequest();
			 xmlHttp.open("POST", "./vote",true);
			 xmlHttp.onreadystatechange=voteSucceeded;
			 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			 xmlHttp.send("key=" + key );
		}
		function voteSucceeded()
		{
			if(xmlHttp.readyState==4)
		 	{
		  		if(xmlHttp.status==200)
		  		{
		  			var strResult = unescape(xmlHttp.responseText);
		  			var arrResult = strResult.split("@@@"); 
		  			document.getElementById(arrResult[0]).innerHTML = 
		  				"<span></span>"+ arrResult[1]+"只兔</a>"; 
		  		}
		  	}
		}
	</script>    
    <link rel="shortcut icon" href="favicon.ico" />
  </head>

  <body>
  
<%
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    String url = userService.createLoginURL(request.getRequestURI());
	String urlLinktext = "Google账号登陆";
	if (user != null){
	    url = userService.createLogoutURL(request.getRequestURI());
	    urlLinktext = "退出";
	}	 
%>
	<div style="width: 100%;" align="center">
		<div class="topLine">
			<div style="float: left;"><img src="images/horse.jpg"/></div>
			<div style="float: left;" class="headline">神马梦想不是浮云。</div>
			<div style="float: right;" class="text"><%=(user==null? "" : user.getNickname()+"|")%><a href="<%=url%>"><%=urlLinktext%></a></div>
		</div>
	</div>
	<div style="clear: both;"/>	
	<div style="width: 100%;" >
		<p></p>
		<form action="/sign" method="post">
		<table width= "800" align="center" class="pubWindow">
			<tr>
				<td colspan="2" align="left" class="wishLine"> 2011, 你神马梦想？年三十了，总要许个愿吧。拜年啦！
				</td>
			</tr>
			<tr>
				<td width="20"></td>
				<td><textarea rows="4" cols="92" name="wish" id="wish"></textarea></td>
			</tr>
			<tr>
				<td colspan="2" align="right" class="wishLine"><input type="submit" value="发布" class="pubButton"/></td>
			</tr>
		</table>      
	    </form>
	<%
	    PersistenceManager pm = PMF.get().getPersistenceManager();
		
		//Formulate the menu and its links	    
	    String[] menuList = {"2011我们最想要...", "查看最新", "Me的梦想记录"};
	    String jspLinkFormat = "<a href=\"wishlist.jsp?m=%d\">%s</a>";
	    int menuVal = WishUtil.parseMenuVal(request.getParameter("m"), 0, 2);
	    String menuHtml = WishUtil.genMenuHtml( menuList, menuVal, jspLinkFormat );
	    
	    
	    //Formulate JDOQL, and query DB
	    List<Wish> wishes = null;
	    String sortAtt = menuVal==0? "votes":"date";
	    String select_query = "select from " + Wish.class.getName() + " order by " + sortAtt + " desc";
	    Query query = pm.newQuery(select_query);
	    if( menuVal==2 ){ //retrieve a user's wishes
	    	if( user != null ){
		    	query.setFilter("author == paramAuthor"); 
				query.declareParameters("java.lang.String paramAuthor");
				wishes = (List<Wish>)query.execute(user);
			}
			else
				wishes = new ArrayList<Wish>();
		 }
		 else //retrieve all users' wishes
	    	wishes = (List<Wish>) query.execute();
	    
	    //Formulate the message
	    String me2ImgLink = "<img src=\"images/metoo.png\" width=\"50px\" height=\"50px\" class=\"middle\" />"; 
	    String strMsg = String.format( "来自普通人的%d个小小梦想......是你想要的么？要就%s. 传说中，人多了，神马会被感动。",
	    	wishes.size(), me2ImgLink );
	    	
	    if( wishes.isEmpty() ){
	    	if( menuVal == 2 ){ //the personal wishlist is empty
	    		if( user == null )
	    			strMsg = String.format("你还未登陆，如果你有<a href=\"%s\">Google账号</a>，无需注册就可以直接登陆,试试吧!", 
	    				userService.createLoginURL(request.getRequestURI()) );
	    		else
	    			strMsg = "你还没有写下你的梦想，没有？年三十饺子都快上桌啦。<br>说出来，分享一下，会快乐。";
	    	}
	    	else //the whole DB is empty;
	    		strMsg = "还没有人许过愿望，神马很空.";
	    }	    	
	%>
		<table width= "800" align="center" class="wishList">
		<tr>
			<td class="msgLine"><%=strMsg%></td>
		</tr>
		<tr height="30"><td class="menu"><%=menuHtml%></td></tr>
	<%  
		if ( !wishes.isEmpty() ) { 
			for (Wish g : wishes) { 
	%>
		<tr>
			<td>
				<table width="100%" class="wish">
					<tr><td>
						<div style="float: left;">
							<ul class="green">
								<li> <a href="#" class="current" id="<%= KeyFactory.keyToString(g.getKey())%>" name="<%= KeyFactory.keyToString(g.getKey())%>"> <span></span>
										<%=g.getVotes()%>只兔</a>
								</li>
								
						</div>
					</td><tr>
					<tr><td class="autoNewline"><%=g.getContent()%></td></tr>
					<tr><td align="left" class="msgLine"> 
						<%=g.getWishDateString()%> &nbsp;来自&nbsp;<%= (g.getAuthor() == null? "路人":g.getAuthor().getNickname()) %>
						<div style="float: right;">
							<ul class="pink">
								<li><a href="#" class="current" onclick="voteViaPost('<%= KeyFactory.keyToString(g.getKey())%>');">
								<span></span>+Me兔
								</a></li>
							</ul>
						</div>
					</td></tr>
				</table>
			</td>
		</tr>
	<%        } //end for wish loop
	    } //end if-else
	    pm.close();
	%>
		</table>
	</div>
	<p></p>
	<div align="center" class="text">© 2011 Yabo-Arber Xu All rights reserved.</div
  </body>
</html>
